<template>
    <div class="xiaoqu">
<!--        查询小区-->
        <span class="from">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="小区名称:">
                <el-input v-model="formInline.user"></el-input>
            </el-form-item>
<!--                //日期-->
            <el-date-picker
                    v-model="value1"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
<!--                //搜索日期-->
            <el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
        </el-form>
        </span>
<!--        新增小区-->
        <div style="margin-bottom: 30px">
            <el-button type="text" @click="resetData" :style="{'background-color':'#409EFF',color:'#fff',textAlign:'center',width:'100px',padding:'10px 0'}">
                <span>新增小区</span>
            </el-button>
<!--            新增小区-->
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="form">
                    <el-form-item label="小区ID" :label-width="formLabelWidth">
                        <el-input v-model="form.communityId" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="小区名称" :label-width="formLabelWidth">
                        <el-input v-model="form.communityName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="所属地区" :label-width="formLabelWidth">
                        <el-cascader
                                :options="addressAll"
                                clearable
                                v-model="address"
                                :props="{value:'label'}"
                                :style="{marginBottom:'25px'}"
                        ></el-cascader>
                        <el-input v-model="form.communityAddress" autocomplete="off" placeholder="请填写详细地址"></el-input>
                    </el-form-item>
                </el-form>
                <div style="margin-left: 50px">
                    <span style="margin-right: 15px;">门店坐标</span>
                    <el-button @click="getLocation">获取位置</el-button>
                    {{location}}
                </div>
<!-------------------------------------------------------------------------------------------------->
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveDate">保 存</el-button>
                </div>
<!--                ---------------------------------------------------------------------------------->
            </el-dialog>
        </div>
<!--        小区列表展示-->
        <template>
            <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    :header-cell-style="{'background-color':'#409EFF',color:'#fff',textAlign:'center'}"
                    :cell-style="{'text-align':'center'}">

                <el-table-column
                        prop="communityId"
                        label="ID">
                </el-table-column>
                <el-table-column
                        prop="communityName"
                        label="名称">
                </el-table-column>
                <el-table-column
                        prop="communityAddress"
                        label="位置">
                </el-table-column>
                <el-table-column
                        prop="communityUserCount"
                        label="用户数量">
                </el-table-column>
                <el-table-column
                        prop="communityShopCount"
                        label="关联门店"
                style="color: #1890FF">
                </el-table-column>
                <el-table-column
                        prop="createTime"
                        label="创建时间">
                </el-table-column>

                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-button  type="text" @click="setShopId(scope.$index)" size="small">查看关联门店</el-button>
                        <el-button @click="handleClick(scope.$index)" type="text" size="small">编辑</el-button>
                        <el-button
                                @click.native.prevent="deleteRow(scope.$index)"
                                type="text"
                                size="small">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>

<!--        删除操作-->
        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%">
            <span>此操作将永久删除该文件是否继续</span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="deleteData">确 定</el-button>
  </span>
        </el-dialog>

<!--        查看关联门店-->
        <div style="margin-bottom: 30px">

            <el-dialog :title="shopTitle" :visible.sync="shopVisible">
                <el-form>
                    <el-form-item>
                        <el-input v-model="shopName" class="shopname"></el-input>
                        <el-button type="primary" @click="shopSelect">搜索</el-button>
                        <el-button type="primary" @click="showAddShop">添加关联门店</el-button>
                    </el-form-item>
                </el-form>
                <el-table
                        :data="shopDate"
                        border
                        style="width: 100%"
                        :header-cell-style="{'background-color':'#409EFF',color:'#fff',textAlign:'center'}"
                        :cell-style="{'text-align':'center'}">

                    <el-table-column
                            prop="shop_number"
                            label="序号">
                    </el-table-column>
                    <el-table-column
                            prop="shop_name"
                            label="名称">
                    </el-table-column>
                    <el-table-column
                            prop="shop_id"
                            label="ID">
                    </el-table-column>
                    <el-table-column
                            prop="shop_sort"
                            label="排序">
                    </el-table-column>
                    <el-table-column
                            prop="shop_address"
                            label="地址">
                    </el-table-column>
                    <el-table-column
                            prop="dingdan_number"
                            label="订单数量">
                    </el-table-column>

                    <el-table-column
                            label="操作">
                        <template slot-scope="scope">
                            <el-button
                                    type="text"
                                    size="small"
                            @click="deleteShop(scope.$index)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-------------------------------------------------------------------------------------------------->
                <div slot="footer" class="dialog-footer">
                    <el-button @click="shopVisible = false">取 消</el-button>
                </div>
                <!--                ---------------------------------------------------------------------------------->
            </el-dialog>
        </div>
<!--        添加关联门店-->
        <div style="margin-bottom: 30px">

            <el-dialog :title="shopTitle" :visible.sync="shopADDVisible">
                <el-form>
                    <el-form-item>
                        <el-input v-model="shopNameMessage" class="shopname"></el-input>
                        <el-button type="primary" @click="shopAddSelect">搜索</el-button>
                    </el-form-item>
                </el-form>
                <el-table
                        :data="shopAddDate"
                        border
                        @selection-change="handleSelectionChange"
                        style="width: 100%"
                        :header-cell-style="{'background-color':'#409EFF',color:'#fff',textAlign:'center'}"
                        :cell-style="{'text-align':'center'}">

                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            prop="shopName"
                            label="名称">
                    </el-table-column>
                    <el-table-column
                            prop="shopId"
                            label="ID">
                    </el-table-column>
                    <el-table-column
                            prop="shopSort"
                            label="排序">
                    </el-table-column>
                    <el-table-column
                            prop="shopAddress"
                            label="坐标">
                    </el-table-column>
                    <el-table-column
                            prop="shopOrderCount"
                            label="订单数量">
                    </el-table-column>

                </el-table>
                <!-------------------------------------------------------------------------------------------------->
                <div slot="footer" class="dialog-footer">
                    <el-button @click="returnShowShop">取 消</el-button>
                    <el-button @click="addShopDate">保 存</el-button>
                </div>
                <!--                ---------------------------------------------------------------------------------->
            </el-dialog>
        </div>

    </div>
</template>

<script>
    export default {
        name:"XiaoQuComponent",
        data() {
            return {
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                value1: '',
                formInline: {
                    user: '',
                    region: ''
                },
                form: {
                    communityId:'',
                    communityName: '',
                    communityAddress:'',
                    communityUserCount:'',
                    communityShopCount:'',
                    createTime:'',
                    region: '',
                },
                tableData: [],
                dialogFormVisible: false,
                dialogTableVisible: false,
                dialogTableVisible2:false,
                dialogVisible: false,
                formLabelWidth: '120px',
                addressAll: [],   //省市区
                address:[], //你选择的地址
                location:"",
                title:"",
                index:"",
                shopVisible:false,
                shopADDVisible:false,
                shopTitle:"查看关联门店",
                shopName:"",
                shopNameMessage:"",
                shopLabelWidth:'50px',
                shopDate:[],
                shop:{
                    shop_name:"",
                    shop_id:"",
                    shop_sort:"",
                    shop_address:"",
                    shop_number:"",
                    dingdan_number:"",
                },
                shopAddDate:[],
                multipleSelection: [] // 用于存储选中行的数组
            }
        },
        created() {
            this.getAllProvinceAndCityList();
            this.refresh();
        },
        methods: {
            //弹出对话框
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
            //数据刷新
            refresh(){
                this.axios.get("/communityListServlet").then(res=>{
                    this.tableData = res.data.list;
                }).catch(err=>{})
            },
            //修改数据显示
            handleClick(index) {
                this.index = 2;
                console.log(index);
                this.dialogFormVisible = true;
                this.title = '编辑小区';
                console.log(this.tableData);
                this.form.communityName = this.tableData[index].communityName;
                this.form.communityAddress = this.tableData[index].communityAddress;
                this.address =(this.tableData[index].communityProvince+","+this.tableData[index].communityCity+","+this.tableData[index].communityDistrict).split(",")
                this.address[2] = this.tableData[index].communityDistrict;
                this.form.communityId = this.tableData[index].communityId;
                console.log(this.form.communityId);
                this.form.communityName = this.tableData[index].communityName;
                this.address[0] = this.tableData[index].communityProvince;
                this.location = this.tableData[index].communityLongitude+","+this.tableData[index].communityLatitude
            },
            //重置数据显示
            resetData(){
                this.index = 1;
                this.dialogFormVisible = true
                this.title = '新增小区'
                this.form.communityId=""
                this.form.communityName=""
                this.form.communityAddress=""
                this.form.communityUserCount=""
                this.form.communityShopCount=""
                this.form.createTime=""
                this.location=""
                this.address=""
            },
            //保存数据
            saveDate(){
                this.dialogFormVisible = false;
                //新增
                if (this.index === 1){
                    this.axios.post("/communityInsertServlet",{
                        community_id:this.form.communityId,
                        community_name:this.form.communityName,
                        community_address:this.form.communityAddress,
                        community_province:this.address[0],
                        community_city:this.address[1],
                        community_district:this.address[2],
                        community_area_code:0,
                        community_latitude: this.location.split(",")[0],
                        community_longitude: this.location.split(",")[1],
                        community_status:1,
                        community_coordinates:this.address + this.form.communityName,
                    },{
                        headers:{'Content-Type' :'application/x-www-form-urlencoded'}
                    }).then((newdate)=>{
                        console.log(newdate.config.data);
                    }).catch(()=>{});
                    setTimeout(()=>{this.refresh()},500);
                }else if (this.index === 2){
                    //修改
                    this.axios.post("/communityUpdateServlet",{
                        community_id:this.form.communityId,
                        community_name:this.form.communityName,
                        community_address:this.form.communityAddress,
                        create_time:this.getDateString(new Date),
                        community_province:this.address[0],
                        community_city:this.address[1],
                        community_district:this.address[2],
                        community_area_code:0,
                        community_latitude: this.location.split(",")[0],
                        community_longitude: this.location.split(",")[1],
                        community_status:1,
                        community_coordinates:this.address + this.form.communityName,
                    },{
                        headers:{'Content-Type' :'application/x-www-form-urlencoded'}
                    }).then((newdate)=>{
                        console.log(newdate.config.data);
                    }).catch(()=>{});
                    setTimeout(()=>{this.refresh()},500);
                }

            },
            //搜索数据
            onSubmit() {
                this.axios.get("/communitySelectServlet", {
                    params:{
                        message:this.formInline.user,
                        startTime: this.getDateString(this.value1[0]),
                        endTime:this.getDateString(this.value1[1]),
                        page:1,
                        size:10,
                        communityName:this.formInline.user,
                    }
                }).then(res=>{
                    console.log(res.data)
                    this.tableData = res.data.list;
                }).catch(err=>{});
            },
            //删除数据
            deleteRow(index) {
                this.dialogVisible = true;
                this.form.communityId = this.tableData[index].communityId;
                console.log(this.form.communityId)
            },
            deleteData(){
                this.dialogVisible = false;
                this.axios.post("/communityDeleteServlet",{
                    community_id:this.form.communityId,
                },{
                    headers:{'Content-Type' :'application/x-www-form-urlencoded'}
                }).then((res)=>{
                    console.log(res)
                }).then(()=>{});
                setTimeout(()=>{this.refresh()},500);
            },
            //获取省市
            getAllProvinceAndCityList() {
                // 获取全国所有省份和城市的列表
                var that = this;
                this.$http
                    .get("https://restapi.amap.com/v3/config/district", {
                        // 高德地图的API
                        params: {
                            key: "39444c57178c072ed26912eab8a9f3d6", // 这个是申请的 Key，读者自行写入
                            keywords: "中国",
                            subdistrict: 3,
                            extensions: "base",
                        },
                    })
                    .then((response) => {
                        console.log(response.data)
                        for(let i = 0;i < response.data.districts[0].districts.length;i++){
                            let provinceMap = new Map();
                            provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
                            provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
                            provinceMap.children = [];
                            that.addressAll.push(provinceMap);  //添加省份
                            for(let j = 0;j < response.data.districts[0].districts[i].districts.length;j++){
                                let cityMap = new Map()
                                cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                                cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                                cityMap.children = [];
                                provinceMap.children.push(cityMap); //添加市
                                for(let k = 0;k <response.data.districts[0].districts[i].districts[j].districts.length;k++){
                                    let areaMap = new Map()
                                    areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                                    areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                                    cityMap.children.push(areaMap);   //添加区县
                                }
                            }
                        }
                    });
            },
            getLocation(){
                this.axios.get("https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=" + this.address.join("") + this.detail).then((loc)=>{
                    console.log(loc);
                    this.location = loc.data.geocodes[0].location;
                    console.log(this.location)
                }).catch(()=>{})
            },
            //封装日期转为字符串的函数
            getDateString(date){
                let yy = date.getFullYear();
                let mm = date.getMonth()+1;
                let dd = date.getDate();
                let hh = date.getHours();
                let mf = date.getMinutes()<10 ? '0'+date.getMinutes() : date.getMinutes();
                let ss = date.getSeconds()<10 ? '0'+date.getSeconds() : date.getSeconds();
                let str = yy + "-" + mm + "-" + dd +" " + hh + ":" + mf + ":" + ss;
                return str;
            },


            //门店操作
            //查看关联门店
            setShopId(index){
                this.shopVisible = true;
                this.form.communityId = this.tableData[index].communityId;
                this.selectAssociateShop();
            },
            //传输关联门店数据
            selectAssociateShop(){
                this.axios.get("/communitySelectAssociateShop",{
                    params:{
                        community_id : this.form.communityId,
                    }
                }).then(res=>{
                    console.log(res.data)
                    this.shopDate = res.data.list;
                }).catch(err=>{})
            },
            //查找门店
            shopSelect(){
              this.axios.get("/selectAssociateLikeShopServlet",{
                  params:{
                      community_id:this.form.communityId,
                      message:this.shopName,
                      page:1,
                      size:10
                  }
              }).then(res=>{
                  console.log(res.data);
                  this.shopDate = res.data.list;
              }).then(()=>{});
            },
            //删除门店
            deleteShop(index){
                this.shop.shop_id = this.shopDate[index].shop_id;
                this.axios.post("/communityDeleteAssociateShop",{
                    shop_id:this.shop.shop_id,
                },{
                    headers:{'Content-Type' :'application/x-www-form-urlencoded'}
                }).then(res=>{
                    console.log(res)
                }).catch(()=>{});
                this.selectAssociateShop();
                this.refresh();
            },
            //点击添加关联门店
            showAddShop(){
                this.shopVisible = false;
                this.shopADDVisible = true;
                this.axios.get("/communityShowAddShopList").then(res=>{
                    console.log(res.data);
                    this.shopAddDate = res.data.list;
                }).catch(()=>{});
            },
            //在添加关联门店中的搜索
            shopAddSelect(){
                this.axios.get("/communityAddAssociateSelectShop",{
                    params:{
                        message:this.shopNameMessage,
                    }
                }).then(res=>{
                    console.log(res.data);
                    this.shopAddDate = res.data.list;
                }).catch(()=>{});
            },
            //在添加关联门店中的取消按钮
            returnShowShop(){
                this.shopVisible = true;
                this.shopADDVisible = false;
            },
            //获取所选行的数据
            handleSelectionChange(val) {
                // val 是一个包含选中行数据的数组
                this.multipleSelection = val;
                console.log('当前选中项', val);
            },
            //在添加关联门店中的确定按钮
            addShopDate(){
                this.shopADDVisible = false;
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    this.axios.post("/communityAddAssociateShop",{
                        shopId:this.multipleSelection[i].shopId,
                        communityId:this.form.communityId,
                        shopSort:this.multipleSelection[i].shopSort,
                    },{
                        headers:{'Content-Type' :'application/x-www-form-urlencoded'}
                    }).then(res=>{
                        console.log(res)
                    }).catch(()=>{})
                }
                this.refresh();
                this.selectAssociateShop();
            }
        },

    }
</script>

<style scoped>
    .xiaoqu{
        height: 1000px;
        padding: 20px;
        /*background-color: deeppink;*/
    }
    .dialog-footer{
        position: relative;
        height: 50px;
    }
    .shopname{
        width: 190px;
        margin-right: 20px;
    }
</style>